import { defineStore } from 'pinia';
import localCache from '@/utils/cache';
import { addCartApi, getCartListApi, delCartApi, putCartApi } from '@/service';
const useCartStore = defineStore('cart', {
  state: () => ({
    cartList: localCache.getCache('cartList') ?? '',
  }),
  actions: {
    //获取
    async getCart() {
      const res = await getCartListApi();
      this.cartList = res.result.map((ele) => {
        ele.selected = false;
        return ele;
      });
      localCache.setCache('cartList', this.cartList);
    },
    //添加
    async addCart(data) {
      await addCartApi(data);
      this.getCart();
    },
    //单个增加
    add(id) {
      const good = this.cartList.find((ele) => ele.id === id);
      good.num++;
    },
    sub(id) {
      const good = this.cartList.find((ele) => ele.id === id);
      good.num--;
    },
    //单个减少
    //修改
    async putCart(id, data) {
      await putCartApi(id, data);
      this.getCart();
    },
    //删除
    async delCart(id) {
      await delCartApi(id);
      this.getCart();
    },
    //全选
    setAll(val) {
      this.cartList.forEach((ele) => {
        ele.selected = val;
      });
    },
  },
  getters: {
    //计算出购物车的数量
    cartsNum() {
      return this.cartList.length;
    },
    //总价格
    totalPrice() {
      if (!!this.cartList) {
        return this.cartList.reduce((prev, item) => {
          return item.selected ? prev + item.s_good.price * item.num : prev;
        }, 0);
      }
    },
  },
});
export default useCartStore;
